<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/13
 * Time: 18:48
 */

namespace App\Http\Controllers\Admin;
use App\Model\Address;
use App\Model\Branch;
use App\Model\Members;
use App\Model\Poundage;
use App\Model\RecordBonus;
use App\Model\RecordList;
use App\Model\RecordTransaction;
use App\Model\ShopGoods;
use App\Model\ShopOrder;
use App\Model\ShopOrderComment;
use App\Model\StoresCenter;
use App\Model\Transaction;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Excel;
use Auth;
use Log;
class OrderController extends BaseController {
	/**
	 * 订单首页
	 */
	public function index() {
		return view('Admin.order');
	}

	/**
	 * 订单管理
	 */
	public function order(Request $request) {
		$data = $request->all();
        $data['keyword'] = empty($data['keyword'])?"":$data['keyword'];
        $orderModel = new ShopOrder;
        $BranchModel = new Branch();
		switch ($data['class']) {
		case 'select': //订单列表
            $Members = new Members();
//            if(!empty($data['keyword']['keyword'])){
//                $userData = $Members->where('members.phone','like','%'.$data['keyword']['keyword'].'%')
//                    ->orWhere('members.user_name','like','%'.$data['keyword']['keyword'].'%')
//                    ->orWhere('shop_order.receipt_name','like','%'.$data['keyword']['keyword'].'%')
//                    ->join('shop_order', 'shop_order.uid', '=', 'members.uid')
//                    ->select('members.uid')->get();
//                $uid = [];
//                if ($userData) {
//                    foreach ($userData as $k => $v) {
//                        $uid[] = $v['uid'];
//                    }
//                }
//                $data['keyword']['uid'] = $uid;
//            }
//            $rico = $orderModel->get_order($data['keyword'],1,0);
            $orderModel = $orderModel
                ->join('members', 'shop_order.uid', '=', 'members.uid')
                ->select(
                    'members.phone',
                    'members.user_name',
                    'members.referrer',
                    'shop_order.*'
                )
                ->where('shop_order.status','!=',0)
//                ->distinct('shop_order.uid')
                ->distinct()
                ->orderBy('id', 'desc');
            if(!empty($data['keyword']['ordertype'])){
                $orderModel = $orderModel->where('shop_order.ordertype',$data['keyword']['ordertype']);
            }
            if(!empty($data['keyword']['createtime'])){
                $orderModel = $orderModel->where('shop_order.createtime','>',strtotime($data['keyword']['createtime'][0]))->where('shop_order.createtime','<',strtotime($data['keyword']['createtime'][1]));
            }
            if(isset($data['keyword']['status'])){
                $orderModel = $orderModel->where('status',$data['keyword']['status']);
            }
            if(!empty($data['keyword']['keyword'])){
                $orderModel = $orderModel->where(function ($orderModel) use ($data) {
                    $orderModel->where('shop_order.ordersn','like','%'.$data['keyword']['keyword'].'%')->orWhere('members.user_name','like','%'.$data['keyword']['keyword'].'%')->orWhere('members.phone','like','%'.$data['keyword']['keyword'].'%');
                });
            }
//            $orderMoney = 0;
//            $orderData = $orderModel->get()->toArray();
//            foreach ($orderData as $v){
//                if ($v['status'] == 1){
//                    $orderMoney += $v['price'];
//                }
//            }
//            var_dump($orderMoney);die;
            $rico = $orderModel->paginate(15);

//            var_dump($rico);exit;
//            $orderMoney = array_sum($rico['price']);
			foreach ($rico as $k => $value) {
				$rico[$k]->createtime = date('Y-m-d H:i:s', $value->createtime);
                $rico[$k]->share_name = Members::where( ['uid'=>  $rico[$k]->referrer ])->value("user_name");
//				$rico[$k]->price = array_sum($value['price']);
//				$rico[$k]->price = sum($value['price']);
//				$rico[$k]->paytime = date('Y-m-d H:i:s',$value->paytime);
                $rico[$k]->couriertime = date('Y-m-d H:i:s',$value->couriertime);
                $rico[$k]->stores_number =  $rico[$k]->stores_number=='0'?'未绑定消费门店':$rico[$k]->stores_number;
                $rico[$k]->stores_name = StoresCenter::where( ['number'=>  $rico[$k]->stores_number ] )->value("shop_name");
                $rico[$k]->stores_name =  $rico[$k]->stores_name ==''?'':$rico[$k]->stores_name;
                $res = Address::where('id',$value['addressid'])->first();
                if ( $rico[$k]->receipt_adr == "" || $rico[$k]->receipt_name == "" || $rico[$k]->receipt_phone == "" ) {
                    $rico[$k]->addres = $res['province'].$res['city'].$res['district'].$res['address'];
                    $rico[$k]->name = $res['name'];
                    $rico[$k]->phone = $res['phone'];
                } else {
                    $rico[$k]->addres = $rico[$k]->receipt_adr;
                    $rico[$k]->name = $rico[$k]->receipt_name;
                    $rico[$k]->phone = $rico[$k]->receipt_phone;
                }
                if($value['uid']){
                    $users = $Members->where(['uid' => $value['uid']])->select('user_name','phone')->first();
                    $rico[$k]->user_name = empty($users['user_name'])?$users['phone']:$users['user_name'];
                    $rico[$k]->user_phone = $users['phone'];
                }
			}

			if ($rico) {
				return ['code' => 1, 'data' => $rico];
			} else {
				return ['code' => 0, 'data' => '没有数据'];
			}
			break;

		case 'detail': //订单详情
			if ($data['id']) {
				$OrderModel = new ShopOrderComment();
				$rico = $OrderModel->find_order($data['id']['id']);
				foreach ($rico as $k => $value) {
					$rico[$k]->createtime = date('Y-m-d H:i:s', $value->createtime);
				}
				if ($rico) {
					return ['code' => 1, 'data' => $rico,'orderData' => $data['id']];
				} else {
					return ['code' => 0, 'data' => '没有数据'];
				}
			}
			break;

        case 'credit2Details': //会员奖励币详情
            if ($data['id']) {
                $rico = unserialize( ShopOrder::where('id',$data['id'])->value( 'last_credit2s' ) );
                if ($rico) {
                    return ['code' => 1, 'data' => $rico ];
                } else {
                    return ['code' => 0, 'data' => '没有数据'];
                }
            }
            break;

			//确认发货
            case 'affirmShipments':
                $data['orderStatus']['status'] = 2;
                $data['orderStatus']['couriertime'] = time();
//                if(!$data['orderStatus']['expressage']){
//                    return ['code' => 0, 'data'=> '快递名称不能为空' ];
//                }
//                if(!$data['orderStatus']['courier_number']){
//                    return ['code' => 0, 'data'=> '快递单号不能为空'];
//                }
                $rico = ShopOrder::where('id',$data['id'])->update(array_only($data['orderStatus'],['expressage','courier_number','remark','status','couriertime']));;
                if($rico){
                    return ['code' => 1, 'data' => '发货成功'];
                } else {
                    return ['code' => 0, 'data' => '发货失败'];
                }
                break;
            case 'affirmReceiving':
                $statusData['status'] = 3;
                $rico = ShopOrder::where('id',$data['id'])->update(array_only($statusData,['status']));
                if($rico){
                    return ['code' => 1 , 'data' => '确认收货成功'];
                } else {
                    return ['code' => 0 , 'data' => '确认收货失败'];
                }
                break;
		}
	}

    /*
    * 导出订单数据
    */
    public function exportOrder(Request $request)
    {
        $orderModel = new ShopOrder;
        $data = $request->all();
        $data = empty($data)?"":$data;
        $data['createtime'] = empty($data['createtime'])?"":explode(',',$data['createtime']);
        $Members = new Members();
        //检测是否有值
        $orderModel = $orderModel->where('status','>',0)
            ->join('members', 'shop_order.uid', '=', 'members.uid')
            ->select(
                'members.phone',
                'members.user_name',
                'members.referrer',
                'shop_order.*'
            )
            ->orderBy('paytime', 'desc');
        unset($data['stores']);
        if(!empty($data['ordertype'])){
            $orderModel = $orderModel->where('shop_order.ordertype',$data['ordertype']);
        }
        if(!empty($data['createtime'])){
            $orderModel = $orderModel->where('shop_order.createtime','>',strtotime($data['createtime'][0]))->where('shop_order.createtime','<',strtotime($data['createtime'][1]));
        }
        if(isset($data['status'])){
            $orderModel = $orderModel->where('status',$data['status']);
        }
        if(!empty($data['keyword'])){
            $orderModel = $orderModel->where(function ($orderModel) use ($data) {
                $orderModel->where('shop_order.ordersn','like','%'.$data['keyword'].'%')->orWhere('members.phone',$data['keyword'])->orWhere('members.user_name','like','%'.$data['keyword'].'%');
            });
        }
        $data=$orderModel->get()->toArray();
        if (empty($data)){
            return redirect('/admin/order/index')->withErrors('数据错误');
        }
        $newData[] =  ['订单编号','下单账号','下单人','推荐人','收货姓名','电话','地址','总金额','支付情况','总数量','商品名称','订单类型','订单状态','下单时间','发货时间','配送方式','快递单号','备注'];
        foreach ($data as $k=>$v){
            $addresInfo = Address::where('id',$v['addressid'])->first();
            $data[$k]['addres'] = empty($v['receipt_adr'])?$addresInfo['province'].$addresInfo['city'].$addresInfo['district'].'...':$v['receipt_adr'];
            $data[$k]['name'] = empty($v['receipt_name'])?$addresInfo['name']:$v['receipt_name'];
            $data[$k]['number1'] = 0;
            $data[$k]['number2'] = 0;
            $data[$k]['number3'] = 0;
            $data[$k]['number4'] = 0;
            $data[$k]['number5'] = 0;
            $data[$k]['number6'] = 0;
            $data[$k]['number7'] = 0;
            $data[$k]['number8'] = 0;
            $data[$k]['number'] = [];
            $data[$k]['goodsname'] = '';
            $data[$k]['specs'] = '';
        
//            $data[$k]['phone'] = MOBILE_PHONE_HIDDEN($addresInfo['phone']);
            $data[$k]['phone'] = empty($v['receipt_phone'])?$addresInfo['phone']:$v['receipt_phone'];//收货电话
            $OrderInfo = ShopOrderComment::where('orderid',$v['id'])->get()->toArray();
            $goodsname = '';
            foreach ($OrderInfo as $item =>$order){
//                if( $v['ordertype'] == 2 ){
                    $goodsname = empty($goodsname)? $order['goodsname'].'：'.$order['number'] :$goodsname.'，'.$order['goodsname'].'：'.$order['number'];
                    $data[$k]['goodsname'] = $goodsname;
                    $data[$k]['specs'] = $order['specs'];
                    $data[$k]['number'][] = $order['number'];
//                }

            }

            $userInfo = Members::where('uid',$v['uid'])->select('name')->first();
            $data[$k]['user'] = $userInfo['name'];
        }
        foreach ($data as $key=>$val){
            $val['number'] = array_sum($val['number']);
            $val['createtime']  = date('Y-m-d H:i:s',$val['createtime']);
            $val['couriertime']  = date('Y-m-d H:i:s',$val['couriertime']);
            if($val['ordertype']==1){
                $val['ordertype'] = '折扣专区';
//                $val['goodsname'] = $val['goodsname'];
//                $val['number'] = $val['number'];

            }
            if($val['ordertype']==2){
                $val['ordertype'] = '新人专区';
                $val['goodsname'] = $val['mall_num'];

            }
            if($val['ordertype']==3){
                $val['ordertype'] = '特价专区';
//                $val['goodsname'] = $val['goodsname'];
//                $val['number'] = $val['number'];
            }
            if($val['status'] == '1'){
                $val['status'] = '已付款';
            }
            if($val['status'] == '2'){
                $val['status'] = '已发货';
            }
            if($val['status'] == '3'){
                $val['status'] = '交易完成';
            }
            if($val['freight'] == '1'){
                $val['freight'] = '自提';
            }
            if($val['freight'] == '0'){
                $val['freight'] = '配送';
            }
           /* switch ( $val['is_first'] ) {
                case 1:
                    $val['is_first'] = '报单';
                    break;
                case 0:
                    $val['is_first'] = '复销';
                    break;
            }*/
//            $newData[] =  ['订单编号','下单账号','下单人','推荐人','收货姓名','电话','地址','总金额','总数量','商品名称','订单类型','订单状态','下单时间','发货时间','配送方式','备注'];
            $val['stores_name'] = StoresCenter::where( [ 'number'=>  $val['stores_number'] ] )->value("shop_name");
            $val['share_name'] = Members::where( ['uid'=>  $val['referrer']])->value("user_name");
            $newData[] = [
                $val['ordersn'],
                $val['phone'],
                $val['user_name'],
                $val['share_name'],
                $val['receipt_name'],
                $val['phone'],
                $val['addres'],
                $val['price'],
                $val['reward_money'],
                $val['number'],
                $val['goodsname'],
                $val['ordertype'],
                //$val['is_first'],
                $val['status'],
                $val['createtime'],
                $val['couriertime'],
                $val['freight'],
                "\t".$val['courier_number']."\t",
                $val['remark']
            ];
        }
        $dataTime = date('Y-m-d');
        Excel::create("订单列表".$dataTime,function ($excel) use ( $newData){
            $excel->sheet('score',function ($sheet) use ( $newData) {
                $sheet->rows( $newData);
            });
        })->export('xls');
    }


    public function downGrade($v, $puid,$share, $money)
    {
        $v['super_team_count'] -= $money;
        $v['achievement'] -= $money;
        //添加小区团队
        $super_small_team_count = json_decode($v['super_small_team_count'], true);
        if ($super_small_team_count) {  //判断是否已有团队业绩
            foreach ($super_small_team_count as $items => $item) {
                if ($share == $v['uid']) {//判断是否已有这个会员的业绩
                    $super_small_team_count[$puid] = [
                        'key' => $puid,
                        'val' => 1,
                        'money' => $money,
                    ];

                }
                if (isset($array[$items]) ? $array[$items] : 0) {
                    $super_small_team_count[$items]['money'] -= $money;
                }
            }
            $super_small_team_count = json_encode($super_small_team_count);

        } else {
            $team_count = [
                $puid => [
                    'key' => $puid,
                    'val' => 1,
                    'money' => $money,
                ]
            ];

            $super_small_team_count = json_encode($team_count);
        }
        $v['super_small_team_count'] = $super_small_team_count; //添加小区团队
        return $v;
    }
    /**
     * 限时购撤销订单
     * @return array
     */
    public function cancelOrderMoney(Request $request)
    {
        //系统设置
        $data = $request->all();
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
        $order = ShopOrder::where('id',$data['id'])->first();
        //订单奖励撤回
        $record = RecordTransaction::where(['id' => $data['id']])->get()->toArray();
        DB::beginTransaction();
        foreach ($record as $k => $v){
            $user = Members::where('uid',$v['uid'])->first();
            if ($v['type'] == 5){
                $bonus = RecordBonus::where('tid',$v['id'])->first();
                $credit2 = RETAIN_TWO($bonus['money'] * (100 - $Poundage['redelivery'] - $Poundage['platform_fee'])/100);
                $credit5 = RETAIN_TWO($bonus['money'] * $Poundage['redelivery']/100);
                $res = Members::where('uid',$user['uid'])->update(['credit2' => ($user['credit2'] - $credit2),'credit5' => ($user['credit5'] - $credit5)]);
                if (!$res){
                    DB::rollback();
                    return ['code' => 0,'data' => '撤回失败'];
                }
            } else {
                $res = Members::where('uid',$user['uid'])->update(['credit2' => ($user['credit2'] + $v['money'])]);
                if (!$res){
                    DB::rollback();
                    return ['code' => 0,'data' => '撤回失败'];
                }
            }
        }
        //订单业绩
        $orderComment = ShopOrderComment::where(['orderid' => $orderId])->get()->toArray();
        $cost_price = 0;
        foreach ($orderComment as $k => $v){
            $cost = ShopGoods::where('id',$v['goodsid'])->value('costprice');
            $cost_price += $v['number'] * $cost;
        }
        //老师业绩撤回
        $type = 0;
        $members = Members::where('uid', '<=', 	$order['uid'])->orderBy('uid', 'desc')->select('uid', 'referrer','level','level_name', 'level_grade','credit1', 'credit2', 'credit3', 'credit4', 'credit5','team_member_count', 'super_recommend', 'super_team_count', 'super_small_team_count', 'super_level', 'super_level_name', 'is_credit3', 'type', 'achievement','team_profit')->get()->toArray();
        $referrer = Members::where('uid',$order['uid'])->value('referrer');
        $arrays = [];
        $share = $referrer;
        foreach ($members as $k => $v) {
            if (!empty($v['referrer'])) {
                if ($referrer == $v['uid']) {//寻找上级id 微客
                    $referrer = $v['referrer'];
                    //会员业绩撤回
                    if ($type == 0) {
                        $arrays[$v['uid']] = $v['referrer'];
                        $v = $this->downGrade($v,$order['uid'], $share, $cost_price);
                    }
                    //上级uid
                    $puid = $v['uid'];
                    //更新会员数据
                    Members::where(['uid' => $v['uid']])->update(
                        [
                            'credit1' => $v['credit1'],
                            'credit2' => $v['credit2'],
                            'credit3' => $v['credit3'],
                            'credit4' => $v['credit4'],
                            'credit5' => $v['credit5'],
                            'level' => $v['level'],
                            'level_name' => $v['level_name'],
                            'super_recommend' => $v['super_recommend'],
                            'super_team_count' => $v['super_team_count'],
                            'super_small_team_count' => $v['super_small_team_count'],
                            'super_level' => $v['super_level'],
                            'super_level_name' => $v['super_level_name'],
                            'is_credit3' => $v['is_credit3'],
                            'achievement' => $v['achievement'],
                        ]);

                }
            }
        }
        DB::commit();
        return ['code' => 1,'data' => '撤回成功'];
    }
    /**
     * 截取价格
     * @param array $array
     * @param $on
     * @return bool
     */
    public function string($array = array(), $on)
    {
        if (preg_match('/\d+/', $array[$on], $arr)) {
            return $arr[0];
        } else {
            return false;
        }
    }
    /**
     * 定时当日订单业务管理加权分红
     */
    public  function weightingBonus(){
//        $time = time();
//        $newTimeH = date('H',$time);
//        $newTimeI = date('i',$time);
//        if($newTimeH != 23){
//            exit('非法请求，已记录你的请求位置。');
//        }
//        if($newTimeI != 58){
//            exit('非法请求，已记录你的请求位置。');
//        }
        //会员表
        $UserModel = new Members();
        //系统设置
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->find_poundage();
//        $date =   date('Y-m-d',time());
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
//        var_dump($beginToday);
        $endToday=mktime(23,59,58,date('m'),date('d'),date('Y'));
//        var_dump($endToday);
        $money = ShopOrder::where('paytime','>=',$beginToday)->where('paytime','<=',$endToday)->where('status','>',0)->sum('price');
//
//        var_dump($money);exit;
        if($money < 1){
            exit('不符合分红条件');
        }
        $members = $UserModel->where('credit3','>','0')->sum('credit3');
        $integral = RETAIN_TWO(($Poundage['bonus']) * $money/100 * $Poundage['management_award']/100/$members);
        $members = $UserModel->where('credit3','>','0')->get()->toArray();
//        DB::beginTransaction(); //开启事务
        foreach ($members as $k => $v){
            $money2 = RETAIN_TWO($integral * $v['credit3']);
//            $money2 = RETAIN_TWO($bonus * $Poundage['bonus']/100);
            $recommendMoney = CALCULATE($Poundage, $money2, 2);
            //添加记录
            $v['credit2'] += $recommendMoney['money'];
            $v['credit5'] += $recommendMoney['redelivery'];
            //记录订单之前各会员的奖励币余额记录
            $res = $UserModel->where('uid',$v['uid'])->update(['credit2' => $v['credit2'],'credit5' => $v['credit5']]);
            //重新赋值
            $addData3['money'] = $money2;
            $addData3['type'] = 5;
            $addData3['text'] = '今日订单业务管理分润';
            $addData3['recommendMoney'] = $recommendMoney;
            $addData3['ordersn'] =  ORDER_SN();;
            if ($res){
                $this->addOrder($v['uid'],  $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
//                    echo 'OK';
            }
        }
        echo 'OK';
    }
    /**
     * 定时当日订单当日订单消费分红
     */
    public  function clearBonus(){
//        $time = time();
//        $newTimeH = date('H',$time);
//        $newTimeI = date('i',$time);
//        if($newTimeH != 23){
//            exit('非法请求，已记录你的请求位置。');
//        }
//        if($newTimeI != 58){
//            exit('非法请求，已记录你的请求位置。');
//        }
        $poundageModel = new Poundage();
            $res = $poundageModel->where('id',1)->update(['subsidy_reward' => 0]);
            if($res){
                echo 'OK';
            }

    }
    /**
     * 添加交易记录
     * @param null $uid 会员id
     * @param null $money 交易总金额
     * @param null $type 交易类型 1 订单 2 转账 3 提现  4充值 5 奖励制度
     * @param string $explain 交易名称
     * @param array $manageMoney 奖励金额 复投金额 平台费金额
     * @param null $company_id 公司id
     */
    public function addOrder($uid = null, $money = null, $type = null, $explain = '', $manageMoney = array(), $company_id = null, $ordersn = '',$remark)
    {
        $ordersn = empty($ordersn) ? ORDER_SN() : $ordersn;
        //交易记录表
        $order_uid = ShopOrder::where('ordersn', $ordersn)->value('uid');
        $userName = Members::where('uid', $order_uid)->value('user_name');
        $RecordTransaction = new RecordTransaction();
        //交易记录表详情表
        $RecordBonus = new RecordBonus();
        $levelinDatas = [ //交易记录
            'uid' => $uid,
            'ordersn' => $ordersn,
            'money' => $money,
            'type' => $type,
            'time' => time(),
            'explain' => $explain,
            'remark' => $remark,
            'company_id' => $company_id,
        ];
        $TransactionId = $RecordTransaction->add_transaction($levelinDatas);
        $bonusData = [//交易详情
            'uid' => $uid,
            'tid' => $TransactionId,
            'money' => $money,
            'remark' => $explain . '：' . $manageMoney['money'] . '，复销币：' . $manageMoney['redelivery'] . '，平台费：' . $manageMoney['platform_fee'],
//            'remark' => $explain . '：' . $money. '，参与积分来源：用户' . $userName . '参与抢购' . ')',
            'time' => time(),
            'type' => 1,
            'company_id' => $company_id,
        ];
        $RecordBonus->add_bonus($bonusData);
    }

    /**
     *订单积分分红
     */
    public function consumption( Request $request )
    {
        $data = $request->all();
        $PoundageModel = new Poundage();
        $Poundage = $PoundageModel->first();
        $UserModel = new Members();
        switch ($data['class']){
            //个人消费积分份额分红
            case 'resale_bonus':
                
            $fp = fopen("lock.txt", "w+");
            if(flock($fp,LOCK_EX | LOCK_NB))
            {         
                
                $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
                $endToday=mktime(23,59,58,date('m'),date('d'),date('Y'));
                $record = RecordList::where('time','>=',$beginToday)->where('time','<=',$endToday)->where('type','=',1)->count();
                if($record){
                    flock($fp,LOCK_UN);
                    return ['code' => 0,'data' => '今日已分红，请勿重复分红!!!'];
                }
                $order = ORDER_SN() ;
                $voucher = $UserModel->where('voucher','>','0')->where('platform_profit',1)->sum('voucher');
                if($data['money'] <= 0){
                    flock($fp,LOCK_UN);
                    exit('请输入正确的分红金额');
                }
                if($voucher <= 0){
                    flock($fp,LOCK_UN);
                    return ['code' => 0,'data' => '暂无分红会员'];
                }
                $integrals = RETAIN_TWO( $data['money']/$voucher);//单份份额
                $nums = $UserModel->where('voucher','>','0')->where('platform_profit',1)->count();
                $members = $UserModel->where('voucher','>','0')->where('platform_profit',1)->where('is_out', 1)->where('credit3','>',0)->get()->toArray();
                foreach ($members as $k => $v){
//                    $micro = ShopOrder::where(['uid' => $v['uid'],'ordertype' => 2])->where('status','>=',1)->value('price');
                    if ($v['consumption_bonus'] > $v['credit3']){
                        //分红上限
                        $results =  $UserModel->where('uid',$v['uid'])->update(['is_out' => 0,'voucher' => 0,'consumption_bonus' => 0]);
                        $RecordTransaction = new RecordTransaction();
                        if ($results){
                            $recommendData = [
                                'uid' => $v['uid'],
                                'ordersn' => $order,
                                'money' => 0,
                                'type' => 1,
                                'time' => time(),
                                'explain' => '已出局',
                                'remark' => '已出局' ,
                            ];
                            $RecordTransaction->add_transaction($recommendData);
                        }
                        unset($members[$k]);
                    }
                }
                if ($data['submit'] == 1){
//                    if(empty($members) ){
//                        return ['code' => 0,'data' => '暂无分红会员'];
//                    }
                    if(empty($data['explain'])){
                        flock($fp,LOCK_UN);
                        return ['code' => 0,'data' => '分红备注不能为空！'];
                    }
                    foreach ($members as $k => $v){
                        $money2 = RETAIN_TWO($integrals * $v['voucher']);
//                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
//                        //添加记录
//                        $v['credit2'] += $recommendMoney['money'];
//                        $v['credit5'] += $recommendMoney['redelivery'];
//                        $v['consumption_bonus'] += $money2;
                        //记录订单之前各会员的奖励币余额记录
                        $res = $UserModel->where('uid',$v['uid'])->update(['achievement_increment' => $money2]);
                        //重新赋值
//                        $addData3['money'] = $money2;
//                        $addData3['type'] = 5;
//                        $addData3['text'] = $data['explain'];
//                        $addData3['remark'] = 1;
//                        $addData3['ordersn'] =  $order;
//                        $addData3['recommendMoney'] = $recommendMoney;
//                        if ($res){
//                            //添加交易记录
//                            $this->addOrder($v['uid'],  $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn'],$addData3['remark'] );
//                        } else {
//                            return ['code' => 0,'data' => '分红失败'];
//                        }
                    }
                    //添加分红日志
                    $RecordList = new RecordList();
                    // 系统操作员
                    $adminUser = Auth::user();
                    $recommendData = [
                        'total_amount' => $data['money'],
                        'user_num' => $nums,
                        'number' => $voucher,
                        'single' => $integrals,
                        'type' => 1,
                        'bonus_sn' => $order,
                        'remark' => $data['explain'] ,
                        'verifier' => $adminUser['user_name'] ,
                        'status' => 0 ,
                        'time' =>time() ,

                    ];
                    $row = $RecordList->add_record($recommendData);
                    if($row){
                        flock($fp,LOCK_UN);
                        return ['code' => 1,'data' => '分红成功'];
                    }

                } else {
                    flock($fp,LOCK_UN);
                    return ['code' => 1,'pre' => $integrals,'count' => $nums,'total'=>$voucher];
                }
                
                
                flock($fp,LOCK_UN);
                
                
            }else{
                return ['code' => 1,'data' => '阻塞处理'];
            }
            
            
            
            fclose($fp);
                break;
            //团队消费积分份额分红
            case 'team_bonus':
                $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
                $endToday=mktime(23,59,58,date('m'),date('d'),date('Y'));
                $record = RecordList::where('time','>=',$beginToday)->where('time','<=',$endToday)->where('type','=',2)->count();
                if($record){
                    return ['code' => 0,'data' => '今日已分红，请勿重复分红!!!'];
                }
                $member = $UserModel->where('credit3','>','0')->where('platform_profit',1)->sum('credit3');
                if($data['money'] <= 0){
                    exit('请输入正确的分红金额');
                }
                if($member <= 0){
                    return ['code' => 0,'data' => '暂无分红会员'];
                }
                $integral = RETAIN_TWO( $data['money']/$member);
                $num = $UserModel->where('credit3','>','0')->where('platform_profit',1)->count();
                $members = $UserModel->where('credit3','>','0')->where('platform_profit',1)->get()->toArray();
//        DB::beginTransaction(); //开启事务
                if ($data['submit'] == 1){
                    if(empty($data['explain'])){
                        return ['code' => 0,'data' => '分红备注不能为空！'];
                    }
                    if(empty($members)){
                        return ['code' => 0,'data' => '暂无分红会员'];
                    }
                    $order = ORDER_SN() ;
                    foreach ($members as $k => $v){
                        $money2 = RETAIN_TWO($integral * $v['credit3']);
//                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
                        //添加记录
//                        $v['credit2'] += $recommendMoney['money'];
//                        $v['credit5'] += $recommendMoney['redelivery'];
//                        $v['team_bonus'] += $money2;
                        //记录订单之前各会员的奖励币余额记录
                        $res = $UserModel->where('uid',$v['uid'])->update(['team_achievement' => $money2]);
                        //重新赋值
//                        $addData3['money'] = $money2;
//                        $addData3['type'] = 5;
//                        $addData3['text'] = $data['explain'];
//                        $addData3['remark'] = 2;
//                        $addData3['recommendMoney'] = $recommendMoney;
//                        $addData3['ordersn'] =  $order;
//                        if ($res){
//                            $this->addOrder($v['uid'],  $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn'],$addData3['remark']);
//
//                        } else {
//                            return ['code' => 0,'data' => '分红失败'];
//                        }
                    }
                    //添加分红日志
                    $RecordList = new RecordList();
                    // 系统操作员
                    $adminUser = Auth::user();
                    $recommendData = [
                        'total_amount' => $data['money'],
                        'user_num' => $num,
                        'number' => $member,
                        'single' => $integral,
                        'type' => 2,
                        'bonus_sn' => $order,
                        'remark' => $data['explain'] ,
                        'verifier' => $adminUser['user_name'] ,
                        'status' => 0 ,
                    ];
                    $rows = $RecordList->add_record($recommendData);
                    if($rows){
                        return ['code' => 1,'data' => '预分红成功'];
                    }
                } else {
                    return ['code' => 1,'pre' => $integral,'count' => $num,'total_num'=>$member];
                }

                break;
            //复投积分份额分红
            case 'new_bonus':
                $members_num = $UserModel->where('is_credit6','>','0')->where('platform_profit',1)->sum('is_credit6');
                if($data['money'] <= 0){
                    exit('请输入正确的分红金额');
                }
                if($members_num <= 0){
                    return ['code' => 0,'data' => '暂无分红会员'];
                }
                $integral = RETAIN_TWO( $data['money']/$members_num);
                $num = $UserModel->where('is_credit6','>','0')->where('platform_profit',1)->count();
                $members = $UserModel->where('is_credit6','>','0')->where('platform_profit',1)->get()->toArray();
//                $members1 = $UserModel->where('is_credit6','>','0')->where('super_recommend','>=',3)->where('share_bonus','<=',990*3)->where('is_read',1)->get()->toArray();
                foreach ($members as $v){
                    $members[] = $v;
                }
//        DB::beginTransaction(); //开启事务
                if ($data['submit'] == 1){
                    if(empty($data['explain'])){
                        return ['code' => 0,'data' => '分红备注不能为空！'];
                    }
                    if(empty($members)){
                        return ['code' => 0,'data' => '暂无分红会员'];
                    }
                    $order = ORDER_SN();
                    foreach ($members as $k => $v){
                        $money2 = RETAIN_TWO($integral * $v['is_credit6']);
//                        $recommendMoney = CALCULATE($Poundage, $money2, 2);
//                        //添加记录
//                        $v['credit2'] += $recommendMoney['money'];
//                        $v['credit5'] += $recommendMoney['redelivery'];
//                        $v['share_bonus'] += $money2;
                        //记录订单之前各会员的奖励币余额记录
                        $res = $UserModel->where('uid',$v['uid'])->update(['single_achievement' => $money2]);
                        //重新赋值
//                        $addData3['money'] = $money2;
//                        $addData3['type'] = 5;
//                        $addData3['text'] = $data['explain'];
//                        $addData3['recommendMoney'] = $recommendMoney;
//                        $addData3['ordersn'] =  ORDER_SN();;
//                        if ($res){
//                            $this->addOrder($v['uid'],  $addData3['money'], 5, $addData3['text'], $addData3['recommendMoney'], 0, $addData3['ordersn']);
//                        } else {
//                            return ['code' => 0,'data' => '分红失败'];
//                        }
                    }
                    //添加分红日志
                    $RecordList = new RecordList();
                    // 系统操作员
                    $adminUser = Auth::user();
                    $recommendData = [
                        'total_amount' => $data['money'],
                        'user_num' => $num,
                        'number' => $members,
                        'single' => $integral,
                        'type' => 3,
                        'bonus_sn' => $order,
                        'remark' => $data['explain'] ,
                        'verifier' => $adminUser['user_name'] ,
                        'status' => 0 ,
                    ];
                    $rows = $RecordList->add_record($recommendData);
                    if($rows){
                        return ['code' => 1,'data' => '预分红成功'];
                    }
                } else {
                    return ['code' => 1,'pre' => $integral,'count' => $num,'total_num'=>$members];
                }
                break;


        }
    }

}

                